import pandas as pd
import numpy as np

movies = pd.read_csv("/Users/andre/Downloads/ml-latest-small/movies.csv")
ratings = pd.read_csv("/Users/andre/Downloads/ml-latest-small/ratings.csv")

def get_rating(movies_df, ratings_df):
	# предварительная группировка
	group_ratings = ratings_df.groupby(
		by=['movieId']
	)['rating'].mean().reset_index()

	# округление до ближайшей половины 0.5
	group_ratings.loc[:,['rating']] = np.round(group_ratings['rating'] * 2) / 2

	# соединение таблиц
	movies_with_avg_rating = movies_df.merge(
	    group_ratings,
		how='left',
	    on='movieId'
	)

	# заполнение NaN
	movies_with_avg_rating.rating.fillna(0, inplace=True)

	# создание и заполнение колонки class
	movies_with_avg_rating.loc[movies_with_avg_rating['rating'] <= 2, 'class'] = 'низкий рейтинг'
	movies_with_avg_rating.loc[ (movies_with_avg_rating['rating'] > 2) & (movies_with_avg_rating['rating'] <= 4), 'class'] = 'средний рейтинг'
	movies_with_avg_rating.loc[ (movies_with_avg_rating['rating'] == 4.5) | (movies_with_avg_rating['rating'] == 5), 'class'] = 'высокий рейтинг'

	movies_with_avg_rating.drop(
		columns=['rating'],
		inplace=True
	)

	return movies_with_avg_rating

get_rating(movies, ratings)
